#!/usr/bin/env bash
#
#
. ./base.sh

function install_redis() {
    [ -d /data/redis/data ] || mkdir -p /data/redis/data
    which redis-server && printf_c "redis already install" || {
        printf_c "install... redis"
       # curl $FTPpath40/redis-2.8.5.tar.gz  -u $FTP_user:$FTP_password -o /usr/local/src/redis-2.8.5.tar.gz && \
	down_stat=`http_download "/update/4.0test/redis-2.8.5.tar.gz" "/usr/local/src/redis-2.8.5.tar.gz"`
	[ $down_stat -eq 0 ] && \
        printf_c "download redis finish" || \
        printf_c "download redis filed" $err_c && \
        cd /usr/local/src && tar fx redis-2.8.5.tar.gz -C /usr/local/src && \
        cd /usr/local/src/redis-2.8.5/ && make clean && make && \
        \cp -f ./src/redis-server /usr/bin/ && \
        \cp -f ./redis.conf /etc/ && \
	redis-server /etc/redis.conf && \
	echo "redis-server /etc/redis.conf" >> /etc/rc.local && \
	printf_c "install redis finish" || \
	printf_c "install redis failed" $err_c
    }

    php -m |grep redis && \
    printf_c "php-redis already installed" || {
        printf_c "install... php-redis"
#	curl $FTPpath40/3.1.4.tar.gz  -u $FTP_user:$FTP_password -o /usr/local/src/3.1.4.tar.gz && \
	http_download "/update/4.0test/3.1.4.tar.gz" "/usr/local/src/3.1.4.tar.gz" && \
	printf_c "download php-redis finish" && \
	cd /usr/local/src && tar fx 3.1.4.tar.gz && cd phpredis-3.1.4 && \
	phpize && \
	./configure --with-php-config=/usr/bin/php-config && \
	make && make install && \
        grep '^extension=redis.so' /etc/php.ini||echo "extension=redis.so">>/etc/php.ini && \
	printf_c "php-redis install finish"
    }

    /root/.pyenv/versions/3.6.2/bin/pip3.6 install redis >> /dev/null && \
    printf_c "python3.6-redis install finish"
}

function java_env() {
    jdkversion=`rpm -qa | grep jdk|head -n 1`
    [ "$jdkversion"x = "jdk1.8-1.8.0_161-fcs.x86_64"x ] && \
    printf_c "jdk already installed" || {
        [ -d /home/bxroot/java ] || mkdir -p /home/bxroot/java
	printf_c "install... jdk"
        #javaconfig="config.tar.gz" && \
        #cd /home/bxroot/java && \
        #curl $FTPpath38/$javaconfig  -u $FTPuser:$FTPpassword -o /home/bxroot/java/$javaconfig && \
        #tar -xf /home/bxroot/java/$javaconfig -C /home/bxroot/java/
        #localip=`ip a|egrep '172.30'|grep -v '232'|awk -F '[ /]+' '{print $3}'`
        #ip4=${localip##*.}
        #sed -i '/active: prod230/s/active: prod230/active: prod'$ip4'/' /home/bxroot/java/config/application.yml
        javainterface="/update/3.8Released/jdk-8u161-linux-x64.rpm"
	printf_c "download... $javainterface"
	down_stat=`http_download $javainterface "/usr/local/src/jdk-8u161-linux-x64.rpm"` && \
	printf_c "download $javainterface finish" || \
	printf_c "download $javainterface failed" $err_c
	
	while [ "$jdkversion"x != ""x ]
	do
	    yum -y remove $jdkversion
	    jdkversion=`rpm -qa | grep jdk|head -n 1`
	done
        rpm -ivh /usr/local/src/jdk-8u161-linux-x64.rpm && \
	printf_c "jdk install finish" || \
	printf_c "jdk install failed" $err_c
    }
}

function mix() {
    localip=$(/sbin/ip addr |grep 172.30 |egrep -v 232|awk -F '[/ ]+' '{print $3}')
    sed -i '/DB_VOD_HOST/c \define ( '"'DB_VOD_HOST'"', '"'$localip'"' );//数据库地址172.27.1.231' /home/bxroot/vod_api/config.inc.php
    sed -i '/DB_VOD_I_HOST/c define ( '"'DB_VOD_I_HOST'"', '"'$localip'"' );\/\/172.27.1.231' /home/bxroot/vod_api/config.inc.php
    grep 'API_CMS_CLICKRECORD' /home/bxroot/vod_api/config.inc.php || sed -ri  '/CMS接口start/i \define ( 'API_CMS_CLICKRECORD', "http://cms.beidousat.com:10021/?m=api&a=saveClickRecordNew" );//上传点播数据' /home/bxroot/vod_api/config.inc.php
    grep 'API_CMS_FORENSICS' /home/bxroot/vod_api/config.inc.php || sed -ri  '/CMS接口start/i \define ( 'API_CMS_FORENSICS', "http://cms.beidousat.com:10021/?m=api&a=saveForensicsNew" );//上传取证歌曲' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_CLICKRECORD/c define ( '"'API_CMS_CLICKRECORD'"', "http://cms.beidousat.com:10021/?m=api&a=saveClickRecordNew" );\/\/上传点播数据' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_FORENSICS/c define ( '"'API_CMS_FORENSICS'"', "http://cms.beidousat.com:10021/?m=api&a=saveForensicsNew" );\/\/上传取证歌曲' /home/bxroot/vod_api/config.inc.php
    sed -i  '/STORE_WEB/c define ( '"'STORE_WEB'"', "http://e.beidousat.com" );\/\/店家域名' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_AD_PLAYLIST/c define ( '"'API_AD_PLAYLIST'"', "http://e.beidousat.com/index.php/Api/PlayList" ); \/\/下载广告列表' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_AD_RUNNING/c define ( '"'API_AD_RUNNING'"', "http://e.beidousat.com/index.php/Api/DeviceRunning" ); \/\/上传设备开机状态' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_AD_STATISTICS/c define ( '"'API_AD_STATISTICS'"', "http://e.beidousat.com/index.php/Api/Statistics" ); \/\/上传消费静态数据' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_AD_SONGLIST/c define ( '"'API_AD_SONGLIST'"', "http://e.beidousat.com/index.php/Api/OrientationSongs" );\/\/定向广告' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_KTVROOM/c define ( '"'API_CMS_KTVROOM'"', "http://cms.beidousat.com:10021/?m=api&a=saveKTVNetRoom" );\/\/上传房间信息' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_STATISTICS/c define ( '"'API_CMS_STATISTICS'"', "http://cms.beidousat.com:10021/?m=api&a=saveStatistics" );\/\/上传ERP静态数据' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_RANKING/c define ( '"'API_CMS_RANKING'"', "http://cms.beidousat.com:10021/?m=api&a=getRanking" );\/\/北星排行下发' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_LOCKSONG/c define ( '"'API_CMS_LOCKSONG'"', "http://cms.beidousat.com:10021/?m=api&a=saveLockSong" );\/\/上传缺歌登记' /home/bxroot/vod_api/config.inc.php
    sed -i '/API_CMS_BATELOG/c define ( '"'API_CMS_BATELOG'"', "http://cms.beidousat.com:10021/?m=api&a=saveBateLog" );\/\/上传BateLog' /home/bxroot/vod_api/config.inc.php
    sed -i '/CLOUD_WEB/c define ( '"'CLOUD_WEB'"', "http://m.beidousat.com:2800/" );\/\/云服务器web地址' /home/bxroot/vod_api/config.inc.php
    sed -i '/CLOUD_SERVER/c define ( '"'CLOUD_SERVER'"', "m.beidousat.com" );\/\/云服务器IP地址' /home/bxroot/vod_api/config.inc.php
    sed -i '/DB_VOD_PW/c define ( '"'DB_VOD_PW'"', '"'dev2018918'"' );' /home/bxroot/vod_api/config.inc.php
    sed -i '/DB_VOD_I_PW/c define ( '"'DB_VOD_I_PW'"', '"'dev2018918'"' );' /home/bxroot/vod_api/config.inc.php
    sed -ri '/STORE_IP/c \define ( '"'STORE_IP',"' "e.beidousat.com" );//店家IP地址' /home/bxroot/vod_api/config.inc.php
#######################
######################
    sed -i '/php4_manage/d' /var/spool/cron/root
    sed -i "/adfiledown.php/d" /var/spool/cron/root
    sed -i '/202.120.2.101/d' /var/spool/cron/root
    sed -i '/jump/d' /var/spool/cron/root
    sed -ri '/pool.ntp.org/c \0 */2 * * * ntpdate cn.pool.ntp.org >/dev/null && hwclock -w' /var/spool/cron/root
    #sed -ri 's/pool.ntp.org/cn.pool.ntp.org\ \&\&\ hwclock/' /var/spool/cron/root
    grep 'cn.pool.ntp.org' /var/spool/cron/root || sed -i '1i \0 */2 * * * ntpdate cn.pool.ntp.org >/dev/null && hwclock -w' /var/spool/cron/root
    sed -i '/dbrsync.sh/d' /var/spool/cron/root
    #grep '^\*\/1 \* \* \* \* sh /server/scripts/check_s3.sh &>/dev/null' /var/spool/cron/root || echo "*/1 * * * * sh /server/scripts/check_s3.sh &>/dev/null">>/var/spool/cron/root
    grep '^00 00 \* \* \* sh /server/scripts/when_rm_song.sh' /var/spool/cron/root || echo "00 00 * * * sh /server/scripts/when_rm_song.sh">>/var/spool/cron/root
    #grep '^\*\/25 \* \* \* \* sh /server/scripts/guard.sh' /var/spool/cron/root || echo "*/25 * * * * sh /server/scripts/guard.sh">>/var/spool/cron/root
    grep '^\*\/10 \* \* \* \* sh /server/scripts/versionupdate.sh' /var/spool/cron/root || echo "*/10 * * * * sh /server/scripts/versionupdate.sh">>/var/spool/cron/root
    #grep '^0 8 \* \* \* sh /server/scripts/cloudSongRsync.sh  &>/dev/null' /var/spool/cron/root || echo "0 8 * * * sh /server/scripts/cloudSongRsync.sh  &>/dev/null">>/var/spool/cron/root
    #sed -ri '/playdata.php/c \*/5 * * * * cd /home/bxroot/vod_api/; /usr/bin/php playdata.php  & >/tmp/playdata.php.out' /var/spool/cron/root
    #sed -r '/bxvodBak.sh/c \0 16 * * * bash /server/scripts/bxvodBak.sh &>/dev/null' /var/spool/cron/root
    grep "keep_run.sh" /var/spool/cron/root || echo "*/5 * * * * bash /server/scripts/keep_run.sh >/dev/null" >> /var/spool/cron/root
    sed -ri '/keep_run.sh/c \*/5 * * * * bash /server/scripts/keep_run.sh >/dev/null' /var/spool/cron/root
    #grep "vod_sync_loop.sh" /var/spool/cron/root || sed -ri "/bxvodBak.sh/a \0 6 * * * bash /server/scripts/vod_sync_loop.sh >/dev/null" /var/spool/cron/root
    grep "origin.sh" /var/spool/cron/root || echo "*/5 * * * * bash $dest_fn >/server/scripts/versionupdate.log" >> /var/spool/cron/root
    #grep "vod_opt.sh" /var/spool/cron/root || echo "0 8 * * * bash /server/scripts/vod_opt.sh" >> /var/spool/cron/root
    #sed -i '/php4/d' /etc/rc.local
    #[ -f /server/scripts/php4_manage.sh ] && \rm -f /server/scripts/php4_manage.sh
    #sed -i '/supervisor/d' /etc/rc.local
    sed -ri "/cloudDownloads_v1/d" /etc/rc.d/rc.local
    /etc/init.d/netdata stop
    chkconfig netdata off
}
#############################

function install_pyenv() {
    cd $HOME
    which pyenv || {
        git clone https://github.com/yyuu/pyenv.git
        mv pyenv .pyenv
        cat > /etc/profile.d/pyenv.sh<< EOF
export PYENV_ROOT="\$HOME/.pyenv"
export PATH="\$PYENV_ROOT/bin:\$PATH"
eval "\$(pyenv init -)"
eval "\$(pyenv virtualenv-init -)"
EOF
	source /etc/profile.d/pyenv.sh
	pyenv install 3.6.2 && pyenv install 2.7.12
        cat > ~/.pip/pip.conf<< EOF
[global]
index-url = http://pypi.douban.com/simple
timeout = 300
[install]
trusted-host=pypi.douban.com
EOF
    }
}

############################################################
mysql <<EOF
UPDATE mysql.user SET password=PASSWORD('dev2018918') WHERE User='dev';
FLUSH PRIVILEGES;
EOF
a=`curl -o /dev/null --retry 3 --retry-max-time 8 -s -w %{http_code} "http://127.0.0.1:2800/??m=index&a=getConfig"`
if [ $a -eq 200 ];then
    #curl ftp://$FTP_user@ftptest.beidousat.com/3.6.5Released/37dbupdate.sql -u  $FTP_user:$FTP_password -o /tmp/37dbupdate.sql && \
    down_stat=`http_download "/update/3.6.5Released/37dbupdate.sql" "/tmp/37dbupdate.sql"`
    [ $down_stat -eq 0 ] && printf_c "download 37dbupdate.sql finish" || \
    printf_c "download 37dbupdate.sql failed"
    [ -f /tmp/37dbupdate.sql ] && mysql -f BX_VOD</tmp/37dbupdate.sql && rm -f /tmp/37dbupdate.sql
fi
mysql BX_VOD<<EOF
ALTER TABLE TB_SongFileDownload
ADD COLUMN Filesize  float(8,2) NULL DEFAULT 0 COMMENT '文件大小(MB)' AFTER DownloadEndTime,
ADD COLUMN DownloadSpeed  float(8,2) NULL DEFAULT 0 COMMENT '下载速率(Mbps)' AFTER Filesize;
EOF
mysql -f BX_VOD_AD <<EOF
ALTER TABLE TB_AD_PlaylistM1_fromSrv
ADD COLUMN FileMD5  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '文件MD5值，以\'|\'按位分割' AFTER ADPics;
ALTER TABLE TB_AD_Playlist_fromSrv
ADD COLUMN FileMD5  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '文件MD5值，以\'|\'按位分割' AFTER ADContent;
ALTER TABLE TB_AD_Playlist_fromSrv1
ADD COLUMN FileMD5  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '文件MD5值，以\'|\'按位分割' AFTER ADContent;
ALTER TABLE TB_AD_Playlist_fromSrv2
ADD COLUMN FileMD5  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '文件MD5值，以\'|\'按位分割' AFTER ADContent;
ALTER TABLE TB_AD_Playlist_fromSrv3
ADD COLUMN FileMD5  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '文件MD5值，以\'|\'按位分割' AFTER ADContent;
EOF
mysql -f BX_VOD <<EOF
ALTER TABLE tmp_singersong 
CHANGE lastUpdate lastUpdate datetime null after SongID,
ADD COLUMN LastUpdateTime datetime null COMMENT '最后更新时间' after lastUpdate,
ADD COLUMN LastUpdateFromCMSTime datetime null after LastUpdateTime,
ADD KEY LastUpdateTime(LastUpdateTime);
ALTER TABLE TB_SongFileDownload
ADD COLUMN Filesize  float(8,2) NULL DEFAULT 0 COMMENT '文件大小(MB)' AFTER DownloadEndTime,
ADD COLUMN DownloadSpeed  float(8,2) NULL DEFAULT 0 COMMENT '下载速率(Mbps)' AFTER Filesize;
CREATE TABLE TB_BackgroundVideo (
  ID int(11) unsigned NOT NULL COMMENT 'id',
  VideoCode varchar(50) NOT NULL COMMENT '歌曲编号，不能重复，格式v+自增id',
  VideoName varchar(30) NOT NULL COMMENT '视频名称',
  VideoType int(11) unsigned NOT NULL DEFAULT '0' COMMENT '视频类型',
  PreviewImg varchar(255) NOT NULL COMMENT '预览图链接',
  FilePath varchar(255) NOT NULL COMMENT '文件路径',
  Size bigint(20) unsigned NOT NULL COMMENT '文件大小',
  Description varchar(255) NOT NULL COMMENT '说明',
  FileMD5 varchar(32) NOT NULL COMMENT '文件MD5',
  Status tinyint(1) NOT NULL DEFAULT '0' COMMENT '状态：-1，删除；0，下架；1，在用',
  UpdateTime datetime NOT NULL COMMENT '修改时间',
  reserve varchar(255) NOT NULL COMMENT '备用字段',
  reserve2 varchar(255) NOT NULL COMMENT '备用字段',
  LastUpdateFromCMSTime datetime NOT NULL COMMENT '最后从CMS同步时间',
  PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='MP3播放背景视频表';
ALTER TABLE TB_Skin MODIFY COLUMN SkinType  int(11) NULL DEFAULT NULL COMMENT '皮肤类型ID' AFTER ID;
ALTER TABLE TB_Skin MODIFY COLUMN SkinCode  varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '皮肤编号' AFTER SkinType;
ALTER TABLE TB_Skin MODIFY COLUMN SkinName  varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '皮肤名称' AFTER SkinCode;
ALTER TABLE TB_Skin MODIFY COLUMN PreviewImg  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '皮肤预览图路径' AFTER SkinName;
ALTER TABLE TB_Skin MODIFY COLUMN FilePath  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '皮肤文件路径' AFTER PreviewImg;
ALTER TABLE TB_Skin MODIFY COLUMN Description  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '皮肤描述' AFTER FilePath;
ALTER TABLE TB_Skin MODIFY COLUMN Status  tinyint(1) NULL DEFAULT NULL COMMENT '状态：-1--删除；0--下架；1--在用' AFTER Description;
ALTER TABLE TB_Skin ADD COLUMN Style  tinyint(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT '0,普通类型；1，定时类型' AFTER LastUpdateTime;
ALTER TABLE TB_Skin ADD COLUMN StartTime  datetime NULL DEFAULT NULL COMMENT '定时开始时间' AFTER Style;
ALTER TABLE TB_Skin ADD COLUMN EndTime  datetime NULL DEFAULT NULL COMMENT '定时结束时间' AFTER StartTime;
ALTER TABLE TB_Skin ADD COLUMN UpdateTime  datetime NULL DEFAULT NULL COMMENT '最后更新时间' AFTER EndTime;
EOF
##############################################################

#fn1="cloudDownloads_v2.1.2.pyc"
#fp1="/home/bxroot/cloud_download"
#fn2="cloudDownloads.ini"
#fp2=$fp1
#fn3="ad2ktv"
#fp3="/home/bxroot/interface"
#fn4="ad2ktv_config.ini"
#fp4=$fp3
#fn5="cms2ktv"
#fp5=$fp3
#fn6="cms2ktv_config.ini"
#fp6=$fp3
#filename=($fn1 $fn2 $fn3 $fn4 $fn5 $fn6)
#filepath=($fp1 $fp2 $fp3 $fp4 $fp5 $fp6)
#
##[ -d /home/bxroot/interface ] || mkdir -p /home/bxroot/interface
##curl ftp://$FTP_user@ftptest.beidousat.com/3.6.5Released/interface37.tar.gz -u $FTP_user:$FTP_password -o /home/bxroot/interface/interface37.tar.gz && \
##printf_c "download interface37.tar.gz finish" || \
##printf_c "download interface37.tar.gz failed" $err_c
##[ -f /home/bxroot/interface/interface37.tar.gz ] && \
##cd /home/bxroot/interface && tar -xf interface37.tar.gz 
#
#for i in {0..5}
#do
#    sleep 3
#    #curl $FTPpath38/${filename[$i]} -u $FTP_user:$FTP_password -o ${filepath[$i]}/${filename[$i]} && \
#    down_stat=`http_download "/update/3.8Released/${filename[$i]}" "${filepath[$i]}/${filename[$i]}"`
#    [ $down_stat -eq 0 ] &&  printf_c "download ${filename[$i]} finish" || \
#    printf_c "download ${filename[$i]} failed" $err_c
#done
#
#    dos2unix /home/bxroot/cloud_download/cloudDownloads.ini
#    sed -i 's/dev2016/dev2018918/' /home/bxroot/interface/ad2ktv_config.ini
#    sed -i 's/dev2016/dev2018918/' /home/bxroot/interface/cms2ktv_config.ini
#    sed -i 's/cms\#\&\@\!/cms\@1\#\!\&/' /home/bxroot/interface/cms2ktv_config.ini
#    sed -ri  '/server_ip/c \server_ip  = 172.30.1.232' /home/bxroot/cloud_download/cloudDownloads.ini
#    sed -ri  '/db_host/c \db_host  = 172.30.1.232' /home/bxroot/cloud_download/cloudDownloads.ini
#    grep 'db_passwd' /home/bxroot/cloud_download/cloudDownloads.ini || sed -ri  '/db_host/a \db_passwd  = dev2018918' /home/bxroot/cloud_download/cloudDownloads.ini
#    sed -ri '/url = http:\/\/120.77.243.173:2800/c \url = http://bdsat.grtn.cn/beijing/home/bxroot/vod_api/data/song/' /home/bxroot/cloud_download/cloudDownloads.ini
#    sed -ri '/url = http:\/\/mt.beidousat.com/c \url = http://mt.beidousat.com/' /home/bxroot/cloud_download/cloudDownloads.ini
#    sed -ri '/HTTP_Host/c \HTTP_Host=http://mt.beidousat.com' /home/bxroot/interface/cms2ktv_config.ini
#    sed -ri '/DB_Host=172.30/c \DB_Host=127.0.0.1' /home/bxroot/interface/cms2ktv_config.ini
#    dos2unix /home/bxroot/interface/cms2ktv_config.ini

ps -eaf |egrep "WorkerMan|cloudDownloads_|2ktv|listen.sh" | grep -v "grep"| awk '{print $2}'|xargs kill -9

src_fn="/update/scripts/hold_up_v4/origin.sh"
dest_fn="/server/scripts/origin.sh"
down_stat=`http_download $src_fn $dest_fn`
[ $down_stat -eq 0 ] && printf_c "download $src_fn finish" || \
printf_c "download $sec_fn failed" $err_c
#>/server/scripts/version.idx

##################################
#printf_c "######## install pyenv #################################"
#install_pyenv
printf_c "######## install redis #################################"
install_redis
/etc/init.d/php-fpm restart
printf_c "######## install java #################################"
java_env
#printf_c "######## change php config #################################"
mix
